<template>
  <template v-if="props.column.dataIndex === 'actions'">
    <a-button type="link" :size="'small'" @click="emits('actions-edit', props.record)"
      >编辑
    </a-button>
    <a-button danger type="link" :size="'small'" @click="emits('actions-delete', props.record)"
      >删除
    </a-button>
  </template>
  <template v-if="props.column.dataIndex === 'role'">
    <a-select
      :value="props.record.role?.id"
      show-search
      label-in-value
      placeholder="Select users"
      style="width: 160px"
      :filter-option="false"
      :not-found-content="state.fetching ? undefined : null"
      :options="state.data"
      @search="fetchUser"
      @change="updateUserRole"
    >
      <template v-if="state.fetching" #notFoundContent>
        <a-spin size="small" />
      </template>
    </a-select>
  </template>
  <template v-else-if="props.column.dataIndex === 'avatar'">
    <img class="custom-avatar" :src="props.record.avatar" alt="" />
  </template>
  <template v-else>
    {{ props.text }}
  </template>
</template>

<script setup lang="ts">
import { defineEmits, defineProps, reactive } from 'vue'
import { debounce } from 'lodash-es'
import { getRolesListApi } from '@/api/role.api.ts'
import { updateUserRoleApi } from '@/api/user.api.ts'

export interface TableActionsProps {
  column: Record<string, string>
  record: Record<string, string>
  index: number
  text: string
  defaultRoleList: Record<string, string>[]
}

const props = defineProps<TableActionsProps>()
const emits = defineEmits(['actions-edit', 'actions-delete', 'editOk'])

const state = reactive({
  data: (props?.defaultRoleList ?? []).map((role) => {
    return {
      label: role.name,
      value: role.id,
    }
  }),
  value: undefined,
  fetching: false,
})
const fetchUser = debounce((value) => {
  state.data = []
  state.fetching = true
  getRolesListApi({ pageNo: 1, pageSize: 10, name: value }).then((res) => {
    state.data = res.records.map((v) => {
      return {
        label: v.name,
        value: v.id,
      }
    })
    state.fetching = false
  })
}, 300)

const updateUserRole = async (value: { value: string }) => {
  const data = { id: value.value }
  await updateUserRoleApi(props.record.id, data)
  emits('editOk')
}

defineOptions({
  name: 'ActionsBtn',
})
</script>
<style scoped>
.custom-avatar {
  width: 30px;
  height: 30px;
  object-fit: cover;
  font-size: 0;
}
</style>
